import { createRouter, createWebHistory ,type RouteRecordRaw } from 'vue-router';
import Index from '../pages/Index.vue';
import Administrater from '../pages/Administrater.vue';
import Main from '../pages/Main.vue';
import Students from '../pages/Students.vue';
import Home from '../pages/Home.vue';
import Questionsettings from '../pages/Questionsettings.vue';
import Singlechoice from '../pages/Singlechoice.vue';
import Judgement from '../pages/Judgement.vue';
import Shortanswer from '../pages/Shortanswer.vue';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/administrater',
    component: Administrater, // 主布局组件
    meta: { requiresAuth: true, role: 'admin' }, // 添加权限元数据
    children: [
      {
        path: '', // 默认子路由，显示首页
        component: Home,
      },
      {
        path: '/home', // 首页
        component: Home,
      },
      {
        path: '/students', // 学生管理
        component: Students,
      },
      {
        path: '/single-choice', 
        component: Singlechoice,
      },
      {
        path: '/question-settings', 
        component: Questionsettings,
      },
      {
        path: '/judgement', 
        component: Judgement,
      },
      {
        path: '/short-answer', 
        component: Shortanswer,
      },
    ],
  },
  {
    path: '/index',
    name: 'Index',
    component: Index,
  },
  {
    path: '/main',
    name: 'Main',
    component: Main,
    meta: { requiresAuth: true, role: 'student' }
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 添加路由守卫进行权限控制
router.beforeEach((to, _from, next) => {
  const userRole = localStorage.getItem('userRole'); // 登录时存储的角色
  
  // 检查路由是否需要认证
  if(to.meta.requiresAuth) {
    if(!userRole) {
      // 未登录跳转到登录页
      next('/index');
    } else if(to.meta.role && to.meta.role !== userRole) {
      // 角色不匹配
      next(userRole === 'admin' ? '/' : '/main'); // 跳转到对应角色的首页
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
